package icu.decade.store.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author qk
 * @version 1.0
 * @className ThreadPoolConfig
 * @description
 * @date 2023/6/20 16:26
 **/
@Data
@Configuration
@EnableConfigurationProperties(ThreadPoolParams.class)
public class ThreadPoolConfig {
    @Autowired
    private ThreadPoolParams threadPoolParams;
    private static final String THREAD_NAME_PREFIX = "store-";

    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        Integer taskCorePoolSize = threadPoolParams.getTaskCorePoolSize();
        Integer taskMaxPoolSize = threadPoolParams.getTaskMaxPoolSize();
        Integer taskQueueCapacity = threadPoolParams.getTaskQueueCapacity();
        Integer taskKeepAliveSeconds = threadPoolParams.getTaskKeepAliveSeconds();
        boolean allowCoreThreadTimeOut = threadPoolParams.isAllowCoreThreadTimeOut();
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(taskCorePoolSize == null ? 10 : taskCorePoolSize);
        taskExecutor.setMaxPoolSize(taskMaxPoolSize == null ? 50 : taskMaxPoolSize);
        taskExecutor.setQueueCapacity(taskQueueCapacity == null ? 50 : taskQueueCapacity);
        taskExecutor.setKeepAliveSeconds(taskKeepAliveSeconds == null ? 100 : taskKeepAliveSeconds);
        taskExecutor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        taskExecutor.setAllowCoreThreadTimeOut(allowCoreThreadTimeOut);
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.initialize();
        return taskExecutor;
    }
}
